package com.mimo.comet.config;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.springframework.stereotype.Component;

import com.mimo.common.rpc.proto.LogicUserProxyGrpc;
import com.mimo.common.rpc.proto.LogicUserProxyGrpc.LogicUserProxyBlockingStub;

import io.grpc.netty.shaded.io.netty.util.internal.ThreadLocalRandom;
import net.devh.boot.grpc.client.inject.GrpcClient;

@Component
public class LogicUserPoolFactory {

  private final List<LogicUserProxyGrpc.LogicUserProxyBlockingStub> holder = new ArrayList<>();

  @PostConstruct
  public void init() throws IllegalAccessException {
    Field[] fields = this.getClass().getDeclaredFields();
    for (Field f : fields) {
      f.setAccessible(true);
      if (f.getType() == LogicUserProxyGrpc.LogicUserProxyBlockingStub.class) {
        holder.add((LogicUserProxyBlockingStub) f.get(this));
      }
    }
  }

  @GrpcClient(value = "logic-user-1")
  private LogicUserProxyGrpc.LogicUserProxyBlockingStub logicUserProxyBlockingStub1;

  @GrpcClient(value = "logic-user-2")
  private LogicUserProxyGrpc.LogicUserProxyBlockingStub logicUserProxyBlockingStub2;

  @GrpcClient(value = "logic-user-3")
  private LogicUserProxyGrpc.LogicUserProxyBlockingStub logicUserProxyBlockingStub3;

  @GrpcClient(value = "logic-user-4")
  private LogicUserProxyGrpc.LogicUserProxyBlockingStub logicUserProxyBlockingStub4;

  @GrpcClient(value = "logic-user-5")
  private LogicUserProxyGrpc.LogicUserProxyBlockingStub logicUserProxyBlockingStub5;

  @GrpcClient(value = "logic-user-6")
  private LogicUserProxyGrpc.LogicUserProxyBlockingStub logicUserProxyBlockingStub6;

  @GrpcClient(value = "logic-user-7")
  private LogicUserProxyGrpc.LogicUserProxyBlockingStub logicUserProxyBlockingStub7;

  @GrpcClient(value = "logic-user-8")
  private LogicUserProxyGrpc.LogicUserProxyBlockingStub logicUserProxyBlockingStub8;

  @GrpcClient(value = "logic-user-9")
  private LogicUserProxyGrpc.LogicUserProxyBlockingStub logicUserProxyBlockingStub9;

  @GrpcClient(value = "logic-user-10")
  private LogicUserProxyGrpc.LogicUserProxyBlockingStub logicUserProxyBlockingStub10;

  public LogicUserProxyGrpc.LogicUserProxyBlockingStub getLogicUserStub() {
    return holder.get(ThreadLocalRandom.current().nextInt(holder.size()));
  }

}
